package runner

import (
	v1 "buildrun.io/runner-helper/api/v1"
	"bytes"
	"errors"
	"github.com/BurntSushi/toml"
	"github.com/vinkdong/gox/log"
	"io/ioutil"
	"sync"
)

type Manager struct {
	Name           string
	ConfigFilename string
	Lock           sync.RWMutex
}

func Start() error {
	log.Infof("start runner manager")
	return nil
}

func LoadFromFile(filename string) *Config {
	tomlData, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Error(err)
		return nil
	}

	var conf Config
	if err := toml.Unmarshal(tomlData, &conf); err != nil {
		log.Error(err)
		return nil
	}
	return &conf
}

func (m *Manager) AddRunner(configuration *v1.SharedConfiguration) error {

	if configuration.Spec.RefRunner != m.Name {
		log.Infof("skip create runner %s , ref runner not %s", configuration.Name, m.Name)
		return nil
	}

	m.Lock.Lock()
	defer m.Lock.Unlock()

	cfg := LoadFromFile(m.ConfigFilename)
	if cfg == nil {
		return errors.New("Runner初始化未完成")
	}

	newRunner := cfg.Runners[0].DeepCopy()
	newRunner.Token = configuration.Spec.Token
	newRunner.Name = configuration.Name

	for _, r := range cfg.Runners {
		if r.Name == configuration.Name {
			return nil
		}
	}

	cfg.Runners = append(cfg.Runners, newRunner)

	var buf bytes.Buffer
	e := toml.NewEncoder(&buf)
	err := e.Encode(cfg)
	if err != nil {
		return err
	}

	return ioutil.WriteFile(m.ConfigFilename, buf.Bytes(), 0755)
}

func (m *Manager) RemoveRunner(name string) error {
	m.Lock.Lock()
	defer m.Lock.Unlock()

	cfg := LoadFromFile(m.ConfigFilename)
	if cfg == nil {
		return errors.New("Runner初始化未完成")
	}

	idx := -1
	for i, r := range cfg.Runners {
		if r.Name == name {
			idx = i
		}
	}
	if idx == -1 {
		log.Warnf("未找到名称为%s的Runner", name)
		return nil
	}

	cfg.Runners = append(cfg.Runners[:idx], cfg.Runners[idx+1:]...)

	var buf bytes.Buffer
	e := toml.NewEncoder(&buf)
	err := e.Encode(cfg)
	if err != nil {
		return err
	}

	return ioutil.WriteFile(m.ConfigFilename, buf.Bytes(), 0755)
}
